#include "ntc.h"
#include "ADC.h"
#include "sys.h"
#include <math.h>

#define REFER_VOLTAGE 5000  /* 参考电压 3.3V,数据精度乘以100保留2位小数*/

void ntc_init(void)
{
    ADC_InitTypeDef __xdata ADC_InitStructure;
    ADC_InitStructure.ADC_SMPduty = 11;
    ADC_InitStructure.ADC_Speed = ADC_SPEED_2X9T;
    ADC_InitStructure.ADC_Power = ENABLE;
    ADC_InitStructure.ADC_AdjResult = ADC_RIGHT_JUSTIFIED;
    ADC_InitStructure.ADC_Priority = Priority_0;
    ADC_InitStructure.ADC_Interrupt = DISABLE;
    ADC_InitStructure.ADC_CsSetup = 0;
    ADC_InitStructure.ADC_CsHold = 1;
    ADC_Inilize(&ADC_InitStructure);
}

void ntc_get_temperature(u8 *temperature)
{
    u16 __xdata adcVal;
    u16 __xdata volt;
    
    float __xdata Rt;           //测得实际电阻值
    float __xdata Temp;         //温度值
    float __xdata R = 10000;     //热敏电阻NTC103
    float __xdata B = 3950;     //NTC固有参数
    float __xdata T2= (273.15+25.0);
    
    static u8 __xdata preTemp = 0xFF;
    static u8 __xdata cnt;

    adcVal = Get_ADCResult(ADC_CH14);

    volt = (adcVal / 1024.0f) * REFER_VOLTAGE; /*换算成电压*/
    // println(volt);
    /* 开路或短路 */
    if(volt > 4800 || volt < 200)
    {
        Temp = 0xFF;
    }
    else
    {
        Rt = 10200.0f * volt / (5000 - volt);
        Temp = 1 / (logf(Rt / R) / B + 1 / T2);
        Temp = (Temp - 273.15);        //最终的温度值
    }

    /* 当被进程中断打断时，会出现Temp = 0的情况 */
    if(Temp == 0 || Temp == 0xFF)
    {
        cnt++;
        if(cnt < 3)
        {
            Temp = preTemp;
        }
    }
    else
    {
        cnt = 0;
        preTemp = Temp;
    }
    *temperature = (u8)Temp;
}

void ntc_func(void)
{
    static u8 __xdata tempTab[8] = {0};
    u8 __xdata temp;
    static u16 __xdata sum = 0;
    static u8 __xdata tabIndex = 0xFF;

    ntc_get_temperature(&temp);
    
    if(temp == 0xFF)
    {
        sysParams.regs.temperatureSmp = 0xFF;
        return;
    }
    /* 第一次读取，初始化缓冲表 */
    if(tabIndex == 0xFF)
    {
        tabIndex = 0;
        for(u8 __xdata i = 0; i < 8; i++)
        {
            tempTab[i] = temp;
        }
        sum = temp * 8;
    }
    sum = sum + temp - tempTab[tabIndex];
    tempTab[tabIndex++] = temp;
    tabIndex %= 8;

    sysParams.regs.temperatureSmp = sum >> 3;
}
